/**
 * File    : OpenIDServerServlet.java
 * Created : 2008-10-13
 * By      : LuHuiguo
 */
package com.luhuiguo.sso.web.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.luhuiguo.sso.provider.OpenIDAuthResponse;
import com.luhuiguo.sso.provider.OpenIDException;
import com.luhuiguo.sso.provider.OpenIDProvider;

/**
 * @author LuHuiguo
 * @version $Id: OpenIDServerServlet.java 11 2008-10-15 13:26:26Z LuHuiguo $
 * 
 */
public class OpenIDServerServlet extends HttpServlet {

	private static final long serialVersionUID = 8754843720830726607L;

//	private static final Logger logger = LoggerFactory
//			.getLogger(OpenIDServerServlet.class);

	private OpenIDProvider openIDProvider;

	public static final String OPENID_AUTHENTICATION_APPLICATION_RESPONSE = (new StringBuilder())
			.append(OpenIDServerServlet.class.getName()).append(
					".openid.auth.app.response").toString();

	public OpenIDServerServlet() {
		openIDProvider = null;
	}

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		WebApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(config.getServletContext());
		openIDProvider = (OpenIDProvider) context.getBean("opinIDProvider");
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			if (request
					.getAttribute(OPENID_AUTHENTICATION_APPLICATION_RESPONSE) != null)
				openIDProvider
						.sendAuthenticationResponse(
								request,
								response,
								(OpenIDAuthResponse) request
										.getAttribute(OPENID_AUTHENTICATION_APPLICATION_RESPONSE));
			else
				openIDProvider.processOpenIDRequest(request, response);
		} catch (OpenIDException e) {
			throw new ServletException("Error servicing OpenID request", e);
		}
	}

}